import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../services/screen_adapter.dart';
import '../widget/mq_text.dart';
import '../widget/mq_button.dart';
import '../config/config.dart';
import '../services/storage.dart';
import '../services/event_bus.dart';

class LoginPage extends StatefulWidget {
  LoginPage({Key key}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  String _username = '';
  String _password = '';


  /// 监听登录页面销毁的事件
  dispose(){
    super.dispose();
    eventBus.fire(new UserEvent('登录成功...'));
  }


  _doLogin() async{
    RegExp reg = new RegExp(r'^1\d{10}$');
    print(_username);
    if(!reg.hasMatch(_username)) {
      Fluttertoast.showToast(
        msg: "手机号格式不正确",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.grey[600],
        textColor: Colors.white,
        fontSize: 16.0
      );
    } else if(_password.length < 6) {
      Fluttertoast.showToast(
        msg: "密码不正确",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1,
        backgroundColor: Colors.grey[600],
        textColor: Colors.white,
        fontSize: 16.0
      );
    } else {
      var api = '${Config.domain}api/doLogin';
      var response = await Dio().post(api, data: {'username': _username, 'password': _password});
      if(response.data['success']) {
        // 保存用户信息
        Storage.setString('userInfo', json.encode(response.data['userinfo']));

        Navigator.pop(context);
      } else {
        Fluttertoast.showToast(
          msg: "${response.data['message']}",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.grey[600],
          textColor: Colors.white,
          fontSize: 16.0
        );
      }
    } 
  }

  @override
  Widget build(BuildContext context) {

    ScreenAdapter.init();

    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.close), 
          onPressed: () => Navigator.pop(context)
        ),
        actions: <Widget>[
          FlatButton(
            onPressed: () {

            }, 
            child: Text('客服')
          )
        ]
      ),
      body: Container(
        padding: EdgeInsets.all(ScreenAdapter.width(20)),
        child: ListView(
          children: <Widget>[
            Center(
              child: Container(
                margin: EdgeInsets.only(top: 30),
                width: ScreenAdapter.width(160),
                height: ScreenAdapter.height(160),
                child: Image.asset('images/mq.png', fit: BoxFit.cover)
              )
            ),
            SizedBox(height: 30),
            MqText(
              text: '请输入用户名',
              onChange: (value) {
                print(value);
                setState(() => _username = value);
              },
            ),
            SizedBox(height: 10),
            MqText(
              text: '请输入密码',
              password: true,
              onChange: (value) {
                setState(() => _password = value);
              }
            ),
            SizedBox(height: 10),
            Container(
              padding: EdgeInsets.all(ScreenAdapter.width(20)),
              child: Stack(
                children: <Widget>[
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Text('忘记密码')
                  ),
                  InkWell(
                    onTap: () => Navigator.pushNamed(context, '/registerFirst'),
                    child: Align(
                      alignment: Alignment.centerRight,
                      child: Text('新用户注册')
                    )
                  )
                ]
              )
            ),
            SizedBox(height: 20),
            MqButton(
              text: '登录',
              color: Colors.red,
              height: 74,
              callback: _doLogin,
            )
          ],
        )
      )
    );
  }
}